package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.AdminAuthorityDao;
import com.rk.kbk.dao.AdminDao;
import com.rk.kbk.model.Admin;
import com.rk.kbk.model.AdminAuthority;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by bilibili on 2017/3/31.
 */

@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/adminAuthority")
public class AdminAuthorityController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AdminAuthorityDao adminAuthorityDao;

    @Autowired
    private AdminDao adminDao;




    /**
     * @更改权限目录
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updateAuthority",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeAddress(String userName,String nick,Long id,String realName,String catalog){
        log.debug("批量添加/修改地址");
        Admin admin=adminDao.findOne(Long.valueOf(id));
        admin.setNickName(nick);
        admin.setRealName(realName);
        admin.setUserName(userName);
        adminDao.save(admin);
        List<AdminAuthority> adminAuthority=adminAuthorityDao.findByAdminId(id);
        adminAuthorityDao.delete(adminAuthority);
        List<String> catalogIdList= Arrays.asList(catalog.split(","));
        List<AdminAuthority> adminAuthorityListNew=new ArrayList<>();
        for(String str:catalogIdList){
            AdminAuthority adminAuthorityNew=new AdminAuthority();
            adminAuthorityNew.setAdminId(id);
            adminAuthorityNew.setCatalogId(Long.valueOf(str));
            adminAuthorityNew.setStatus(1);
            adminAuthorityListNew.add(adminAuthorityNew);
        }
        adminAuthorityDao.save(adminAuthorityListNew);
        return JsonResp.ok();
    }

    /**
     * @根据id获取权限列表
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getCatalogByAdminId",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getCatalogByAdminId(Long id) {
        log.debug("批量删除管理员(永久)");
        List<AdminAuthority> adminCatalogList = adminAuthorityDao.findByAdminIdAndStatus(id,1);
        return JsonResp.ok(adminCatalogList);
    }




}
